package com.settlement.system.controller;

import cn.hutool.core.util.IdUtil;
import com.settlement.system.common.enums.AccountStatusEnum;
import com.settlement.system.common.enums.CostAllocationEnum;
import com.settlement.system.common.exception.ServiceException;
import com.settlement.system.model.entity.common.*;
import com.settlement.system.service.*;
import com.settlement.system.common.util.common.DictionaryUtil;
import com.settlement.system.common.util.common.FasUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.fastjson2.JSON;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * RR-费用分摊表 前端控制器
 * @author xiaochuan
 * @since 2023-01-06
 */

@Slf4j
@Api(tags = "RR-费用分摊表",description = "RR-费用分摊表")
@RestController
@RequestMapping("/tblCostAllocationDetail/manualImport")
public class TblCostAllocationDetailManualImportController extends ExcelController<TblCostAllocationDetailManualImport> {

    @Value("${system.export-root.path}")
    private String exportRootPath;
    
    @Resource
    private ITblCostAllocationDetailService tblCostAllocationDetailService;

    @Resource
    private ITblReceiveRefundShopService tblReceiveRefundShopService;

    @Resource
    private ITblRrChannelService tblRrChannelService;

    @Resource
    private ITblRrBillTypeService tblRrBillTypeService;

    @Resource
    private ITblRrRecordProjectMainService tblRrRecordProjectMainService;

    @Resource
    private ITblRrVoucherTypeService tblRrVoucherTypeService;

    @Resource
    private IBrandUnitService brandUnitService;

    @Resource
    private ITblOrderChannelShopsService tblOrderChannelShopsService;

    @Resource
    private ITblReceiveRefundSupplierService tblReceiveRefundSupplierService;

    @Resource
    private IBrandService brandService;

    @Resource
    private DictionaryUtil dictionaryUtil;


    private ExecutorService executors = Executors.newFixedThreadPool(1);

    @Override
    public IBaseService init() {
        return tblCostAllocationDetailService;
    }

    @Override
    public Class<?> getModelClass() {
        return TblCostAllocationDetailManualImport.class;
    }

    @Override
    protected void setParamsModel(Map<String, Object> model) {
        FasUtil.formatInQueryCondition(model,
                "channelNo","shopNo",
                "recordAccountProject","voucherType",
                "accountStatus","pushFasStatus",
                "accountingPeriod"
        );
        String summaryId = (String) model.get("summaryId");
        if(StringUtils.isNotEmpty(summaryId) && summaryId.contains(",")){
            String[] split = summaryId.split(",");
            List<String> summaryIdList = Arrays.asList(split);
            model.put("summaryIdList",summaryIdList);
        }

        super.setParamsModel(model);
    }

    @Override
    public String verifyImportObject(TblCostAllocationDetailManualImport tblCostAllocationDetail, AnalysisContext analysisContext) {

        try{
            Map<String ,Object> params = new HashMap<>(16);
            String s = super.verifyImportObject(tblCostAllocationDetail, analysisContext);
            if(StringUtils.isNotEmpty(s)){
                return s;
            }

            String brandUnitNo = tblCostAllocationDetail.getBrandUnitNo();
            BrandUnit byBrandUnitNo = brandUnitService.getByBrandUnitNo(brandUnitNo);
            if(byBrandUnitNo == null){
                return "品牌部编码不正确或未配置";
            }

            String channelNo = tblRrChannelService.getNoByName(tblCostAllocationDetail.getChannelName());
            if(StringUtils.isEmpty(channelNo)){
                return "[渠道]必须为【RR-渠道设置】中的渠道名称；";
            }
            tblCostAllocationDetail.setChannelNo(channelNo);

            String billType = tblCostAllocationDetail.getBillType();
            String billTypeNo = tblRrBillTypeService.getNoByName(billType);
            if(StringUtils.isEmpty(billTypeNo)){
                return "[账单类型]必须为【RR-账单类型】中的账单类型";
            }
            tblCostAllocationDetail.setBillType(billTypeNo);

            if (CollectionUtils.isEmpty(tblRrRecordProjectMainService.getByRecordAccountProject(tblCostAllocationDetail.getRecordAccountProject()))) {
                return "[记账项目]必须为【RR-记账项目】中的记账项目";
            }

            TblRrVoucherType byVoucherType = tblRrVoucherTypeService.getByVoucherType(tblCostAllocationDetail.getVoucherType());
            if(byVoucherType==null){
                return "[凭证类型]必须为【RR-凭证类型】中的凭证类型";
            }

            /*String beforeOrAfterTicket = byVoucherType.getBeforeOrAfterTicket();
            if(!tblCostAllocationDetail.getBeforeOrAfterTicket().equals(beforeOrAfterTicket)){
                return "[票前票后]跟【RR-凭证类型】中配置的不一致";
            }*/

            TblReceiveRefundShop shop = tblReceiveRefundShopService.getByShopNo(tblCostAllocationDetail.getShopNo());
            if(shop==null){
                return "[店铺编码]必须为【RR-店铺设置】中的零售店铺编码";
            }
            tblCostAllocationDetail.setShopName(shop.getShopName());
            tblCostAllocationDetail.setCompanyNo(shop.getNcEnterAccountBody());

            params.put("threeLevelChannelNo",shop.getThreeChannelNo());
            FasUtil.formatInQueryCondition(params,"threeLevelChannelNo");
            List<TblOrderChannelShops> orderChannelShopsList = tblOrderChannelShopsService.selectByParam(params);


            /*List<String> collect = orderChannelShopsList.stream().map(TblOrderChannelShops::getOrganTypeNo).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(orderChannelShopsList) || CollectionUtils.isEmpty(collect) || !collect.contains("U010102")){
                params.clear();
                params.put("nameShort",tblCostAllocationDetail.getBrandUnitNameShort());
                List<BrandUnit> brandUnitList = brandUnitService.selectByParam(params);
                if (CollectionUtils.isEmpty(brandUnitList)) {
                    return "[品牌简称]必须为现零售主数据中的[品牌简称]";
                }
            }*/

            BigDecimal add = tblCostAllocationDetail.getNoTaxAmount().add(tblCostAllocationDetail.getTaxAmount());
            int i = tblCostAllocationDetail.getShareAmount().compareTo(add);
            if(i!=0){
                return "需要满足条件 分摊金额=不含税金额+税额";
            }


            List<String> nameShortShowChildBrandNameList = dictionaryUtil.getNameShortShowChildBrandNameList();
            if(!CollectionUtils.isEmpty(nameShortShowChildBrandNameList) &&
                    nameShortShowChildBrandNameList.contains(tblCostAllocationDetail.getBrandUnitNo())){
                if(StringUtils.isEmpty(tblCostAllocationDetail.getBrandNo())){
                    return "品牌编码不能为空";
                }

                Brand brandByNo = brandService.getBrandByNo(tblCostAllocationDetail.getBrandNo());
                if(brandByNo == null){
                    return "品牌编码不正确或未配置";
                }

                TblCostAllocationDetail ncBrand = tblCostAllocationDetailService.getNcBrandByBrandNo(tblCostAllocationDetail.getBrandNo());
                if(ncBrand!=null){
                    tblCostAllocationDetail.setNcBrandName(ncBrand.getNcBrandName());
                    tblCostAllocationDetail.setNcBrandNo(ncBrand.getNcBrandNo());
                }
            }else{
                TblCostAllocationDetail ncBrand = tblCostAllocationDetailService.getNcBrandByBrandUnitNo(tblCostAllocationDetail.getBrandUnitNo());
                if(ncBrand!=null){
                    tblCostAllocationDetail.setNcBrandName(ncBrand.getNcBrandName());
                    tblCostAllocationDetail.setNcBrandNo(ncBrand.getNcBrandNo());
                }
            }

            String isJoinRecordAccount = tblRrRecordProjectMainService.getIsJoinRecordAccount(tblCostAllocationDetail.getRecordAccountProject(),
                    tblCostAllocationDetail.getChannelNo(),
                    tblCostAllocationDetail.getBillType());
            if(StringUtils.isEmpty(isJoinRecordAccount)){
                return "是否参与记账，在记账项目设置中未配置";
            }

            List<TblReceiveRefundSupplier> tblReceiveRefundSuppliers = tblReceiveRefundSupplierService
                    .selectByNcSupplierRecord(tblCostAllocationDetail.getNcSupplierRecord());
            if(CollectionUtils.isEmpty(tblReceiveRefundSuppliers)){
                return "NC供应商档案必须为【RR-供应商设置】中的供应商档案";
            }

            if("Y".equals(isJoinRecordAccount)){
                tblCostAllocationDetail.setAccountStatus(AccountStatusEnum.T0_NOT_CREATED.getNo());
            }else if("N".equals(isJoinRecordAccount)){
                tblCostAllocationDetail.setAccountStatus(AccountStatusEnum.T7_NO_NEED_CREATE.getNo());
            }

            if(CostAllocationEnum.BeforeOrAfterTicketEnum.AFTER.getNo().equals(tblCostAllocationDetail.getBeforeOrAfterTicket())){
                tblCostAllocationDetail.setPushFasStatus(CostAllocationEnum.PushFasStatusEnum.T0_NOT_NEED_PUSHING.getNo());
            }else if(CostAllocationEnum.BeforeOrAfterTicketEnum.BEFORE.getNo().equals(tblCostAllocationDetail.getBeforeOrAfterTicket())){
                tblCostAllocationDetail.setPushFasStatus(CostAllocationEnum.PushFasStatusEnum.T1_NOT_PUSHED.getNo());
            }

            setDefualt(tblCostAllocationDetail);
            String idStr = IdUtil.getSnowflake().nextIdStr();
            tblCostAllocationDetail.setSummaryId(idStr);
            tblCostAllocationDetail.setId(null);
            tblCostAllocationDetail.setSourceType(CostAllocationEnum.SourceTypeEnum.T2_MANUAL.getNo());

        }catch (Exception ex){
            log.error("导入失败",ex);
            return "导入校验失败";
        }

        return null;
    }

    @Override
    protected void saveData(List<TblCostAllocationDetailManualImport> datas) throws ServiceException {
        List<TblCostAllocationDetail> collect = datas.stream().map(item -> JSON.parseObject(JSON.toJSONString(item), TblCostAllocationDetail.class)).collect(Collectors.toList());
        tblCostAllocationDetailService.save(collect);
    }
}

